const express = require("express");
const { createServer } = require("http");
const { Server } = require("socket.io");

const app = express();
const httpServer = createServer(app);
const io = new Server(httpServer, {
  /* options */
  cors: {
    origin: "*",
  },
});

let count = 0;

// socket 连接
io.on("connection", (socket) => {
  console.log("有客户端进来了");

  // 给当前客户端发一个消息
  socket.emit("show", count);

  socket.on("incre", () => {
    count++;

    socket.emit("show", count);
    socket.broadcast.emit("show", count);
  });

  socket.on("decre", () => {
    count--;

    socket.emit("show", count);
    socket.broadcast.emit("show", count);
  });

  // 监听客户端发来的消息
  socket.on("message", (data) => {
    console.log(data);
  });

  // 监听 abcd 事件
  socket.on("abcd", (payload) => {
    console.log("服务端 abcd 被触发了", payload);

    // 给当前客户端也发一个消息
    // socket.emit("abcd", "收到了，你发来的是" + payload);

    // 给其他客服端广播消息
    socket.broadcast.emit("abcd", "HELLO");
  });

  // 给自己会消息
  socket.emit("message", {
    message: "hello",
  });

  // 给其它用户广播
  socket.broadcast.emit("message", {
    message: "hello",
  });
});

httpServer.listen(3000);
